/**
 * 应用配置模块
 * 统一管理所有配置项，从环境变量读取
 */

import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 根据环境加载对应的.env文件
const env = process.env.NODE_ENV || 'development';
const envFile = `.env.${env}`;

dotenv.config({ path: path.resolve(__dirname, '../../', envFile) });
dotenv.config(); // 加载默认.env文件作为后备

/**
 * 应用配置对象
 */
export const config = {
  // 环境配置
  env: process.env.NODE_ENV || 'development',
  port: parseInt(process.env.PORT) || 3000,

  // 数据库配置
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT) || 3306,
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    name: process.env.DB_NAME || 'aiessay_dev',
    dialect: 'mysql',
    pool: {
      max: 10,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
    logging: process.env.NODE_ENV === 'development' ? console.log : false,
  },

  // JWT配置
  jwt: {
    secret: process.env.JWT_SECRET || 'your-secret-key-change-in-production',
    expiresIn: process.env.JWT_EXPIRES_IN || '7d',
  },

  // Volces AI API配置
  volces: {
    apiKey: process.env.VOLCES_API_KEY || '',
    apiUrl:
      process.env.VOLCES_API_URL ||
      'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
    model: process.env.VOLCES_MODEL || 'deepseek-v3-1-terminus',
    timeout: parseInt(process.env.VOLCES_TIMEOUT) || 30000,
    maxRetries: parseInt(process.env.VOLCES_MAX_RETRIES) || 3,
  },

  // OCR配置
  ocr: {
    maxImageSize: parseInt(process.env.OCR_MAX_IMAGE_SIZE) || 10 * 1024 * 1024, // 10MB
    timeout: parseInt(process.env.OCR_TIMEOUT) || 30000,
    language: process.env.OCR_LANGUAGE || 'chi_sim+eng',
  },

  // 文件上传配置
  upload: {
    maxFileSize: parseInt(process.env.UPLOAD_MAX_FILE_SIZE) || 10 * 1024 * 1024, // 10MB
    allowedMimeTypes: ['image/jpeg', 'image/png', 'image/jpg'],
  },

  // CORS配置
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
    credentials: true,
  },

  // 日志配置
  logging: {
    level: process.env.LOG_LEVEL || 'info',
    dir: process.env.LOG_DIR || 'logs',
  },

  // 速率限制配置
  rateLimit: {
    windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
    max: parseInt(process.env.RATE_LIMIT_MAX) || 100, // 限制100次请求
  },
};

/**
 * 验证必需的配置项
 * @throws {Error} 当必需配置缺失时抛出错误
 */
export const validateConfig = () => {
  const requiredConfigs = [
    { key: 'jwt.secret', value: config.jwt.secret },
    { key: 'database.password', value: config.database.password },
  ];

  const missing = requiredConfigs.filter(
    (item) => !item.value || item.value === 'your-secret-key-change-in-production'
  );

  if (missing.length > 0 && config.env === 'production') {
    throw new Error(
      `Missing required configuration: ${missing.map((m) => m.key).join(', ')}`
    );
  }
};

// 导出配置为默认导出
export default config;

